#include "virtual_camera/VirtualCamera.hpp"


VirtualCamera::VirtualCamera(std::string video_path)
: video_path(video_path) {
    int idx = video_path.find_last_of('.');
    std::string end_with = video_path.substr(idx + 1);
    if (this->picture_type.find(end_with) != this->picture_type.end()) {
        this->is_picture = true;
    } else {
        this->is_picture = false;
    }
}

VirtualCamera::~VirtualCamera() {
    this->close();
}

int VirtualCamera::open() {
    if (!is_picture) {
        try {
            cam.open(video_path);
        } catch (const std::exception& e) {
            std::cerr << e.what() << '\n';
        }
        
        this->is_opened = cam.isOpened();
    }
    return (this->is_opened ? 0 : -1);
}

int VirtualCamera::close() {
    is_opened = false;
    this->cam.release();
    return 0;
}

cv::Mat VirtualCamera::getFrame() {
    if (!this->is_opened) {
        this->open();
    }

    cv::Mat frame;
    if (!is_picture) {
        // 尝试获取视频图片，如果视频结束则尝试重置视频
        bool status = cam.read(frame); 
        if (!status) {
            std::cout << "视频结束, 重新读取" << std::endl;
            cam.set(cv::CAP_PROP_POS_AVI_RATIO, 0);
            status = cam.read(frame);
            if (!status) {
                std::cout << "视频结束, 重新读取失败" << std::endl;
                raise(SIGINT);
            }
        }
    } else {
        // 读取图片
        frame = cv::imread(this->video_path);
        this->is_opened = false;
        if (frame.empty()) {
            std::cout << "无法打开图片: " << this->video_path << std::endl;
            raise(SIGINT);
        }
    }
    return frame;
}
